package com.sinodata.bsm.cicp.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.sinodata.bsm.common.vo.ProtocolParameter;

/**
 * 
 * <p>
 * Description: HTTP工具类
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-5-21 上午11:30:42   liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class HttpUtil {

    /**
     *
     */
    public HttpUtil() {

    }

    /**
     * 获取HTTP账号密码
     * 
     * @param url
     * @return
     */
    public static String[] getURLAccount(String url) {
        ProtocolParameter protocolParameter = ProtocolParameterUtil.getHttpValue(url);
        if (protocolParameter != null) {
            String usr = protocolParameter.getUserName();
            String pwd = protocolParameter.getPwd();
            return new String[] { usr, pwd };
        } else {
            return null;
        }
    }

    /**
     * 获取HTTP请求返回内容
     * 
     * @param urlStr
     * @return
     * @throws Exception
     */
    public static String getHttpContext(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection connection = null;
        StringBuffer sb = new StringBuffer();
        String line;
        BufferedReader in = null;
        String[] account = getURLAccount(urlStr);
        if (account == null) {
            return null;
        }
        String username = account[0];
        String passwd = account[1];
        String userPassword = username + ":" + passwd;
        String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
        try {
            connection = (HttpURLConnection) url.openConnection();
            if (username != null) {
                connection.setDoOutput(true);
                connection.setRequestProperty("Authorization", "Basic " + encoding);
            }

            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            while ((line = in.readLine()) != null) {
                if (line.contains("<!DOCTYPE")) {
                    continue;
                }
                sb.append(line + "\n");
            }
        } catch (Exception e) {
            throw e;
        } finally {
            in.close();
            connection.disconnect();
        }
        return sb.toString();
    }

}
